<?php

namespace services\common;

use Yii;
use common\components\Service;
use common\models\common\Provinces;

class ProvincesServer extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return Provinces|null
     */
    public function findById(int $id = 0): ?Provinces
    {
        return Provinces::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return Provinces|null
     */
    public function findInfo(array $condition = []): ?Provinces
    {
        $query = Provinces::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['title']) && $query->andWhere(['title' => $condition['title']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Provinces::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        // isset($condition['id']) && $query->andWhere(['id' => $condition['id']]);
        isset($condition['other']) && $query->andWhere($condition['other']);

        return $query->asArray()->all();
    }

    /**
     * 获取城市列表
     *
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public function getCityList()
    {
        $city = Yii::$app->redis->get('city');
        if ($city) {
            // TODO 需求调整，删除缓存
            // Yii::$app->redis->del('city');
            return json_decode($city, true);
        }

        // 直辖市
        $cityIds = [
            Provinces::CITY_BEIJING,
            Provinces::CITY_TIANJIN,
            Provinces::CITY_SHANGHAI,
            Provinces::CITY_CHONGQING,
            Provinces::CITY_HK,
            Provinces::CITY_MO
        ];

        /*$city = $this->findList([
            'select' => ['id', 'title AS name'],
            'other' => [
                'or',
                [
                    'and',
                    ['level' => [Provinces::LEVEL_CITY]],
                    ['not in', 'pid', $cityIds],
                ],
                ['id' => $cityIds],
            ],
        ]);*/

        $city = $this->findList([
            'select' => ['id', 'title AS name'],
            'other' => [
                'or',
                ['level' => [Provinces::LEVEL_CITY, Provinces::LEVEL_AREA]],
                ['id' => $cityIds],
            ],
        ]);

        Yii::$app->redis->set('city', json_encode($city), 'ex', 3600*24*30);

        return $city;
    }
}
